/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.upload.blacklist;

import cn.com.taiji.sdk.model.comm.protocol.AbstractSdtsRequest;
import cn.com.taiji.sdk.tools.JsonTools;
import com.wttech.dzzf.process.dao.BlackListInfoDao;
import com.wttech.dzzf.process.model.UploadRsp;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.ExecuteTable.CARDBLACKLIST;
import static com.wttech.dzzf.process.constant.ExecuteTable.OBUBLACKLIST;

/**
 * 黑名单重传服务
 * @author MaShibo
 * @date 2017/12/25.
 */
@Service
public class BlackListUploadAgainService {

	private static final Logger LOGGER = LoggerFactory.getLogger(BlackListUploadAgainService.class);

	@Resource
	private BlackListInfoDao blackListInfoDao;

	@Resource
	private ThreadPoolTaskExecutor executor;

	@Resource
	private BaseInfoService baseInfoService;

	@Resource
	private BlackListUploadService blackListUploadService;

	private void process(){
		while (true){
			List<UploadRsp> rsps = blackListInfoDao.queryBlListErrorRsp();
			if (CollectionUtils.isEmpty(rsps)){
				executor.shutdown();
				LOGGER.info("执行完毕");
				return;
			}
			List<Future<Void>> futures = new ArrayList<>(rsps.size());
			rsps.forEach(rsp -> futures.add(executor.submit(() -> {
				processUploadRsp(rsp);
				return null;
			})));
			baseInfoService.getFutureResult(futures);
		}
	}

	private void processUploadRsp(UploadRsp rsp){
		String type = rsp.getType();
		Class<? extends AbstractSdtsRequest> cls = CARDBLACKLIST.getStorePath().equals(type) ? CARDBLACKLIST.getRequestType():
				OBUBLACKLIST.getRequestType();
		try {
			AbstractSdtsRequest request = JsonTools.json2Object(rsp.getRequest(), cls);
			blackListUploadService.upload(request, rsp.getInfoId());
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		BlackListUploadAgainService service = context.getBean(BlackListUploadAgainService.class);
		service.process();
	}
}
